//
//  HomeSettingViewController.m
//  hardkorr
//
//  Created by 魏延(颜魏) on 2022/10/21.
//

#import "HomeSettingViewController.h"
#import "ProgressHUD.h"
#import "BTManager.h"

@interface HomeSettingViewController ()

@property (weak, nonatomic) IBOutlet UILabel *stateLabel;
@property (weak, nonatomic) IBOutlet UISwitch *sw;

@property (weak, nonatomic) IBOutlet UIButton *timeBtn;
@property (weak, nonatomic) IBOutlet UIView *typeView;

@property (nonatomic, assign) NSInteger time;

@property (nonatomic, assign) NSInteger queryOrder;     //查询指令
@property (nonatomic, strong) NSTimer   *getSettingTimer;
@property (nonatomic, strong) NSData   *sleepData;
@property (nonatomic, assign) BOOL isOperating;
@property (nonatomic, assign) NSInteger resultCount;

@end

@implementation HomeSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.resultCount = 0;
    
    self.typeView.layer.borderColor = [[[UIColor whiteColor] colorWithAlphaComponent:0.5] CGColor];
    self.typeView.layer.borderWidth = 1;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveData:) name:kBTDidReciveData object:nil];

    self.sw.transform = CGAffineTransformScale(self.sw.transform, 0.8, 0.8);
    self.time = 7;

    self.queryOrder = 0;
    WeakSelf
    self.getSettingTimer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if (weakSelf.isOperating) return;
        if (weakSelf.sleepData) return;
//        [self querySleepInfo]; //4.4 休眠参数读取
        switch (self.queryOrder) {
            case 0:
                [self queryBatteryAndOtherInfo]; //3.4 主控读取电池其他信息
                break;
            case 1:
                [self querySleepInfo]; //4.4 休眠参数读取
                self.queryOrder = -1;
                break;
            default:
                break;
        }
        self.queryOrder++;
        if (self.queryOrder>2) {
            [ProgressHUD hideHUD];
        }
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.getSettingTimer invalidate];
    self.getSettingTimer=nil;
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)actionSync:(id)sender {
    if (!self.sw.on) return;
    if (!self.sleepData) {
        [ProgressHUD showInfoMessage:NSLocalizedString(@"Data acquisition failed, please try again later!", nil)];
        return;
    }
    long basicIndex = 1;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Confirm", nil) message:NSLocalizedString(@"Are you sure you want to change the battery settings?", nil) preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.resultCount = 0;
        long d1,d2,d3,d4,d5,d6,d7;
        Byte *data_array=(Byte*)self.sleepData.bytes;
        d1=data_array[3]*256+data_array[3+1];
        d2=self.time * 60 * 24;
        d3=data_array[3+2*2]*256+data_array[3+2*2+1];
        d4=data_array[3+3*2]*256+data_array[3+3*2+1];
        d5=(data_array[3+4*2]*256+data_array[3+4*2+1]);
        d6=(data_array[3+5*2]*256+data_array[3+5*2+1]);
        d7=data_array[3+6*2]*256+data_array[3+6*2+1];

        if (basicIndex==1) //休眠功能
        {
            if (data_array) {
                int length=0x07+0x08*2+0x02;
                Byte write_array[length];
                write_array[0] = 0x01;//
                write_array[1] = 0x10;//
                write_array[2] = 0x23;//
                write_array[3] = 0x10;//
                write_array[4] = 0x00;//
                write_array[5] = 0x8;//
                write_array[6] = 0x8*2;//
                
                for (int t=0;t<16;t++)
                {
                    write_array[7+t]=data_array[t+3];
                }
                write_array[7] = [self getHighByte:d1];
                write_array[8] = [self getLowByte:d1];
                write_array[9] = [self getHighByte:d2];
                write_array[10] = [self getLowByte:d2];
                write_array[11] = [self getHighByte:d3];
                write_array[12] = [self getLowByte:d3];
                write_array[13] = [self getHighByte:d4];
                write_array[14] = [self getLowByte:d4];
                write_array[15] = [self getHighByte:d5];
                write_array[16] = [self getLowByte:d5];
                write_array[17] = [self getHighByte:d6];
                write_array[18] = [self getLowByte:d6];
                write_array[19] = [self getHighByte:d7];
                write_array[20] = [self getLowByte:d7];
                
                NSData *tempData;
                tempData=[NSData dataWithBytes:write_array length:length];
               
                NSLog(@"sync:%@",@"同步休眠数据");
                [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:length];
                [self refetchData];
            }
        }
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (void)refetchData {
    [ProgressHUD showActivityMessageInWindow:NSLocalizedString(@"Retrieve setting...", nil) timer:2];
    self.queryOrder = 0;
    self.isOperating = NO;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        self.sleepData = nil;
//    });
}

- (IBAction)actionSwitchChanged:(UISwitch *)sender {
    if (!self.sleepData) {
        [ProgressHUD showInfoMessage:NSLocalizedString(@"Data acquisition failed, please try again later!", nil)];
        return;
    }
    self.isOperating = YES;
    self.stateLabel.text = self.sw.on ? @"ON" : @"OFF";
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Confirm", nil) message:NSLocalizedString(@"Are you sure you want to change the battery settings?", nil) preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self turnOnOffFunction:0x55 OnoffType:sender.on];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        sender.on = !sender.on;
        self.stateLabel.text = self.sw.on ? @"ON" : @"OFF";
        self.isOperating = NO;
    }]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (IBAction)actionDownList:(id)sender {
    if (!self.sleepData) {
        [ProgressHUD showInfoMessage:NSLocalizedString(@"Data acquisition failed, please try again later!", nil)];
        return;
    }
    if (!self.sw.on) return;
    self.typeView.hidden = !self.typeView.hidden;
    self.isOperating = !self.typeView.hidden;
}

- (IBAction)actionType:(UIButton *)sender {
    self.isOperating = YES;
    if (!self.sw.on) return;
    if (sender.tag == 100) {
        self.time = 7;
        [self.timeBtn setTitle:@"7 Days" forState:UIControlStateNormal];
    }else if (sender.tag == 101) {
        self.time = 15;
        [self.timeBtn setTitle:@"15 Days" forState:UIControlStateNormal];
    }else if (sender.tag == 102) {
        self.time = 30;
        [self.timeBtn setTitle:@"30 Days" forState:UIControlStateNormal];
    }else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Inactivity period", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UITextField *timeIntervalTextfield = alertController.textFields.firstObject;
            NSString *timeInterval = timeIntervalTextfield.text;
            if (timeInterval.integerValue>0) {
                self.time = [timeInterval integerValue];
                [self.timeBtn setTitle:[NSString stringWithFormat:@"%@ Days", timeInterval] forState:UIControlStateNormal];
            }
        }]];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = NSLocalizedString(@"Enter custom inactivity period(days)  Cancel", nil);
            textField.keyboardType = UIKeyboardTypeNumberPad;
        }];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    self.typeView.hidden = YES;
}

- (void)didReciveData:(NSNotification*)noti {
    if (self.isOperating) return;
    NSData *Notidata=noti.object;
    Byte *dataBytes=(Byte*)Notidata.bytes;
        
    if (dataBytes[2]==0x18) //3.4 主控读取电池其他信息
    {
        BOOL modeInfo= (dataBytes[7] & 0x02) > 0 ? 1 : 0;
        [self.sw setOn:modeInfo];
        self.stateLabel.text = self.sw.on ? @"ON" : @"OFF";
        return;
    }
    if  (dataBytes[2]==0x10)  //4.4 休眠参数读取
    {
//        int modeInfo = dataBytes[3] * 256 + dataBytes[3 + 1];
//        if (modeInfo != 0) {
//            [self.sw setOn:modeInfo>2305];
//            self.stateLabel.text = self.sw.on ? @"ON" : @"OFF";
//        }

        NSInteger min = dataBytes[3+2]*256+dataBytes[3+2+1];
        self.time = ceil(min/(24*60));
        self.sleepData = [NSData dataWithData:Notidata];
        NSLog(@"self.sleepData========%@", self.sleepData);
        [self.timeBtn setTitle:[NSString stringWithFormat:@"%ld Days", self.time] forState:UIControlStateNormal];
        return;
    }
    if ((dataBytes[1]==0x10) || (dataBytes[1]==0x01))//设置成功
    {
        if (self.resultCount > 0) return;
        UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(@"Parameter setting succeeded", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
        [Alert show];
        self.sleepData = nil;
        self.resultCount += 1;
        return;
    }
    if ((dataBytes[1]==0x90) || (dataBytes[1]==0x86))//设置失败
    {
        if (self.resultCount > 0) return;
        UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(@"Parameter setting failed", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [Alert show];
        self.sleepData = nil;
        self.resultCount += 1;
        return;
    }
}

-(void)queryBatteryAndOtherInfo //3.4 主控读取电池其他信息
{
    
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x03;//
    write_array[2] = 0xd1;//
    write_array[3] = 0x15;//
    write_array[4] = 0x00;//
    write_array[5] = 0x0c;//
    write_array[6] = 0x6d;//
    write_array[7] = 0x37;//
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

-(void)querySleepInfo //4.4 休眠参数读取
{
    
    Byte write_array[8];
    write_array[0] = 0x01;//
    write_array[1] = 0x03;//
    write_array[2] = 0x23;//
    write_array[3] = 0x10;//
    write_array[4] = 0x00;//
    write_array[5] = 0x08;//
    write_array[6] = 0x4e;//
    write_array[7] = 0x4d;//
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

-(void)turnOnOffFunction:(int)commandType OnoffType:(BOOL)onOffType
{
    int onOffValue=0x02;
    if (onOffType==0) onOffValue=0x03;
    Byte write_array[8];
    write_array[0] = 0x01;
    write_array[1] = 0x06;
    write_array[2] = 0x11;
    write_array[3] = onOffValue;
    write_array[4] = 0x00;
    write_array[5] = 0x0A;
    write_array[6] = 0x00;
    write_array[7] = 0x00;
    [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:8];
    [self refetchData];
}

-(int)getHighByte:(long)value
{
    return (int)value/256;
}

-(int)getLowByte:(long)value
{
    return (int)(value-(value/256)*256);
}


@end
